const express = require('express');
const superagent = require('superagent');
const charset = require('superagent-charset');
const cheerio = require('cheerio');
const fs = require('fs');
const request = require('request');

const app = express();

async function run(task, ...args) {
    try {
        await task && task(...args);
        console.log('Task Done!');
    } catch(e) {
        console.error('Task Over!');
        
    }
}

async function savePics(res){
    const numToFour = number => {
        number = number.toString().split('');
        while(number.length < 4) {
            number.unshift('0');
        }
        return number.join('');
    }
    const getUrl = index => {
        return `https://www.apple.com.cn/105/media/us/macbook-pro-14-and-16/2021/a1c5d17e-d8e4-4fa8-b70a-bc61bd266412/anim/hero-specs//large/large_${numToFour(index)}.jpg`;
    }
    const downloadUrl = (url,i) => {
        let stream = fs.createWriteStream(`./images/test/${i}.jpg`);
        
        let req = superagent.get(url)
        .set('Cookie', 'geo=CN; s_cc=true; dssf=1; dssid2=eb4b90ea-60cb-4076-ae23-02119d63151a; as_pcts=rFURRIkUHp6RPhTRyeRqWECDU+U5VyxRFUzNkuMYG0OW+poZ0J1nzKPlNJMRTg+rMxmnKT_o:yZjn2QB-w9zds+bAywmboQjWpADzIM2gE+D8SzgfRQIs6; HTML_VisitCountCookie=NaN; as_sfa=Mnxjbnxjbnx8emhfQ058Y29uc3VtZXJ8aW50ZXJuZXR8MHwwfDE; at_check=true; s_sq=appleglobal%3D%2526c.%2526a.%2526activitymap.%2526page%253Dmac%252520-%252520index%25252Ftab%252520%252528cn%252529%2526link%253Dlearn%252520more%252520about%252520macbook%252520pro%252520-%252520%25252Fmacbook-pro-14-and-16%25252F%252520-%252520hero%2526region%253Dhero%2526pageIDType%253D1%2526.activitymap%2526.a%2526.c%2526pid%253Dmac%252520-%252520index%25252Ftab%252520%252528cn%252529%2526pidt%253D1%2526oid%253Dhttps%25253A%25252F%25252Fwww.apple.com.cn%25252Fmacbook-pro-14-and-16%25252F%2526ot%253DA; mk_epub=%7B%22btuid%22%3A%221uwiwty%22%2C%22prop57%22%3A%22www.cn.macbookpro14and16%22%7D')
        .set('Content-Type', 'image/jpeg')
        // console.log(stream);
        req.pipe(stream);
        res.write(`Pic ${i} downloaded! \n`);
    }
    downloadUrl('https://www.apple.com.cn/105/media/us/macbook-pro-14-and-16/2021/a1c5d17e-d8e4-4fa8-b70a-bc61bd266412/anim/hero-specs//large/large_0001.jpg?a=1', 2)
    // let i = 0;
    // while(i <= 1) {
    //     let _url = getUrl(i);
    //     downloadUrl(url, i);
    //     i++;
    // }
}

app.get('/', async (req, res) => {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', "PUT,GET,POST,DELETE,OPTIONS");
    res.header('Access-Control-Allow-Headers', "X-Requested-With");
    res.header('Access-Control-Allow-Headers', "Content-Type");
    // res.setHeader('Content-type', 'application/octet-stream');
    res.write('Local data saved. Start to build dist。files.\n');

    await run(savePics, res);

    res.write('Done!')
    res.end();

})

app.listen(3333, () => {
    console.log('GO!')
})


